import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/common/theme/app_colors.dart';
import 'package:flutter_taotaoshipin/http/dao/drama_dao.dart';
import 'package:flutter_taotaoshipin/model/drama_main_search_entity.dart';
import 'package:flutter_taotaoshipin/pages/drama/drama_routes.dart';
import 'package:flutter_taotaoshipin/pages/home/home_routes.dart';
import 'package:flutter_taotaoshipin/pages/root_tab/root_tab_controller.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/widget/index_banner.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:flutter_taotaoshipin/widget/refresh_footer.dart';
import 'package:flutter_taotaoshipin/widget/refresh_header.dart';
import 'package:flutter_taotaoshipin/widget/refresh_status_view.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';

import 'home_controller.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  final controller = Get.find<HomeController>();
  final state = Get.find<HomeController>().state;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.app_main,
        title: GestureDetector(
          onTap: () {
            Get.toNamed(AppRoutes.search);
          },
          child: Container(
            height: 38,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30),
              color: Colors.white,
            ),
            child: Row(
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(17, 10, 10, 10),
                  child: LoadAssetImage(
                    'home/search',
                    width: 18,
                    height: 18,
                  ),
                ),
                Text(
                  '请输入剧名搜索',
                  style: TextStyle(
                    color: Color(0xFF999999),
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      body: RefreshStatusView(
        controller: controller,
        contentBuilder: (_) {
          return SmartRefresher(
            controller: controller.refreshController,
            // 下拉刷新
            enablePullDown: true,
            header: const RefreshHeader(),
            onRefresh: controller.onRefresh,
            // 加载更多
            enablePullUp: true,
            footer: const RefreshFooter(),
            onLoading: controller.onLoadMore,
            child: CustomScrollView(
              slivers: [
                _buildBanner(),
                _buildItems(),
                ..._buildWeek(),
                ..._buildMainList(),
              ],
            ),
          );
        },
      ),
    );
  }

  _buildBanner() {
    if (state.bannerList.isEmpty) {
      return SliverToBoxAdapter();
    }

    return SliverToBoxAdapter(
      child: Padding(
        padding: EdgeInsets.only(top: 12),
        child: IndexBanner(
          bannerList: state.bannerList,
          aspectRatio: 375 / 305,
        ),
      ),
    );
  }

  _buildItems() {
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            _buildItem(
              'home/item1',
              '追剧',
              onTap: () {
                Get.toNamed(HomeRoutes.collect);
              },
            ),
            _buildItem(
              'home/item2',
              '榜单',
              onTap: () {
                Get.toNamed(HomeRoutes.ranking);
              },
            ),
            _buildItem(
              'home/item3',
              '历史',
              onTap: () {
                Get.toNamed(HomeRoutes.history);
              },
            ),
            _buildItem(
              'home/item4',
              '我的',
              onTap: () {
                RootTabController tab = Get.find();
                tab.switchTap(3);
              },
            ),
          ],
        ),
      ),
    );
  }

  _buildItem(String image, String title, {Function()? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          LoadAssetImage(
            image,
            width: 70,
            height: 70,
          ),
          Text(
            title,
            style: TextStyle(
              color: Color(0xFF333333),
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  _buildWeek() {
    if (state.homeList.isEmpty) {
      return [];
    }

    double itemWidth = (Get.width - 17 * 2 - 9 * 4) / 3;
    double itemHeight = itemWidth / 102 * 143 + 40;
    return [
      SliverToBoxAdapter(
        child: Container(
          margin: EdgeInsets.fromLTRB(17, 0, 17, 0),
          padding: EdgeInsets.fromLTRB(9, 16, 12, 13),
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(8)),
          ),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  '本周热门',
                  style: TextStyle(
                    color: Color(0xFF333333),
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {
                  controller.changeWeekRecommend();
                },
                child: Row(
                  children: [
                    LoadAssetImage(
                      'home/refresh',
                      width: 14,
                      height: 14,
                    ),
                    SizedBox(width: 3),
                    Text(
                      '刷新',
                      style: TextStyle(
                        color: Color(0xFF999999),
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 17),
        sliver: DecoratedSliver(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(bottom: Radius.circular(8)),
          ),
          sliver: SliverPadding(
            padding: EdgeInsets.symmetric(horizontal: 9),
            sliver: SliverGrid.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                crossAxisSpacing: 9,
                mainAxisSpacing: 9,
                mainAxisExtent: itemHeight,
              ),
              itemBuilder: (_, index) {
                var model = state.homeFilterList[index];
                return GestureDetector(
                  onTap: () {
                    // 跳转视频详情页
                    Get.toNamed(DramaRoutes.detail, arguments: {
                      'id': model.dramaId,
                      'title': model.dramaName,
                    });
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Stack(
                        children: [
                          AspectRatio(
                            aspectRatio: 102 / 143,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: LoadImage(model.bookImg ?? ''),
                            ),
                          ),
                          Positioned(
                            left: 0,
                            bottom: 0,
                            right: 0,
                            child: Container(
                              width: double.infinity,
                              alignment: Alignment.bottomRight,
                              padding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 4),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.vertical(
                                    bottom: Radius.circular(8)),
                                gradient: LinearGradient(
                                  colors: [
                                    Colors.transparent,
                                    Color(0x99000000),
                                  ],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                ),
                              ),
                              child: Text(
                                '全${model.dramaAllEp}集',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 10,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 12),
                      Text(
                        model.dramaName ?? '',
                        style: TextStyle(
                          color: Color(0xFF333333),
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                        maxLines: 1,
                      ),
                    ],
                  ),
                );
              },
              itemCount: state.homeFilterList.length,
            ),
          ),
        ),
      ),
    ];
  }

  _buildMainList() {
    if (state.mainList.isEmpty) {
      return [];
    }

    double itemWidth = (Get.width - 17 * 2 - 7 * 2) / 3;
    double itemHeight = itemWidth / 110 * 152;
    return [
      SliverToBoxAdapter(
        child: Padding(
          padding: EdgeInsets.all(17),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  '微短剧推荐',
                  style: TextStyle(
                    color: Color(0xFF333333),
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 17),
        sliver: SliverGrid.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 7,
            mainAxisSpacing: 20,
            mainAxisExtent: itemHeight,
          ),
          itemBuilder: (_, index) {
            var model = state.mainList[index];
            return GestureDetector(
              onTap: () {
                // 跳转视频详情页
                Get.toNamed(DramaRoutes.detail, arguments: {
                  'id': model.id,
                  'title': model.title,
                });
              },
              child: Stack(
                children: [
                  AspectRatio(
                    aspectRatio: 110 / 152,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: LoadImage(model.cover ?? ''),
                    ),
                  ),
                  Positioned(
                    left: 0,
                    bottom: 0,
                    right: 0,
                    child: Container(
                      width: double.infinity,
                      alignment: Alignment.center,
                      padding: EdgeInsets.symmetric(horizontal: 4, vertical: 4),
                      decoration: BoxDecoration(
                        borderRadius:
                            BorderRadius.vertical(bottom: Radius.circular(8)),
                        gradient: LinearGradient(
                          colors: [
                            Colors.transparent,
                            Color(0x99000000),
                          ],
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                        ),
                      ),
                      child: Text(
                        model.title ?? '',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                        maxLines: 1,
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
          itemCount: state.mainList.length,
        ),
      ),
    ];
  }
}
